<template>
  <el-dialog
    v-model="visible"
    :title="
      isEdit ? `编辑维度 - ${dimensionData.dimension_name || ''}` : '创建维度'
    "
    width="800px"
    destroy-on-close
    :before-close="handleBeforeClose"
  >
    <div v-loading="props.loading || metadataLoading" class="form-container">
      <!-- 预定义模板选择（仅创建模式） -->
      <el-card
        v-if="!isEdit && predefinedTemplates.length > 0"
        class="form-section-card template-card"
      >
        <template #header>
          <span class="section-title">快速创建（使用模板）</span>
        </template>
        <el-select
          v-model="selectedTemplate"
          placeholder="选择预定义模板快速创建"
          style="width: 100%"
          @change="handleTemplateSelect"
          clearable
        >
          <el-option
            v-for="template in predefinedTemplates"
            :key="template.name"
            :label="template.name"
            :value="template"
          >
            <div>
              <div style="font-weight: 500">{{ template.name }}</div>
              <div class="option-description">{{ template.description }}</div>
            </div>
          </el-option>
        </el-select>
        <div class="hint-text">选择模板后，将自动填充对应的维度配置</div>
      </el-card>

      <!-- 基础信息 -->
      <el-card class="form-section-card">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-form
          ref="baseFormRef"
          :model="dimensionData"
          label-width="120px"
          size="small"
        >
          <el-form-item
            label="所属模板 *"
            prop="template_id"
            :rules="[
              { required: true, message: '请选择所属模板', trigger: 'change' },
            ]"
          >
            <el-select
              v-model="dimensionData.template_id"
              placeholder="输入模板名称搜索"
              :disabled="isEdit"
              :loading="templateLoading"
              filterable
              remote
              :remote-method="handleTemplateSearch"
              clearable
              @focus="handleTemplateFocus"
              @clear="handleTemplateClear"
            >
              <el-option
                v-for="template in templates"
                :key="template.id || template.template_id"
                :label="template.name || template.template_name"
                :value="template.id || template.template_id"
              >
                <span>{{ template.name || template.template_name }}</span>
                <span
                  v-if="template.code || template.template_code"
                  style="color: #8492a6; font-size: 12px; margin-left: 10px"
                >
                  ({{ template.code || template.template_code }})
                </span>
              </el-option>
              <el-option
                v-if="templates.length === 0 && !templateLoading"
                disabled
                value=""
              >
                {{
                  templateSearchQuery
                    ? "未找到匹配的模板"
                    : "请输入模板名称搜索"
                }}
              </el-option>
            </el-select>
            <div
              v-if="
                templates.length === 0 &&
                !templateLoading &&
                templateSearchQuery
              "
              class="hint-text error-text"
            >
              未找到匹配的模板，请尝试其他关键词
            </div>
            <div
              v-else-if="templates.length === 0 && !templateLoading"
              class="hint-text"
            >
              请输入模板名称进行搜索
            </div>
          </el-form-item>

          <el-form-item
            label="维度代码 *"
            prop="dimension_code"
            :rules="[
              { required: true, message: '请输入维度代码', trigger: 'blur' },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message: '只能包含字母、数字和下划线',
                trigger: 'blur',
              },
              { max: 50, message: '维度代码不能超过50个字符', trigger: 'blur' },
            ]"
          >
            <el-input
              v-model="dimensionData.dimension_code"
              placeholder="请输入维度代码（英文小写+下划线）"
              :disabled="isEdit"
              maxlength="50"
              show-word-limit
            ></el-input>
            <div v-if="!isEdit" class="hint-text">
              提示: 唯一标识，建议使用英文小写+下划线，同一模板下不能重复
            </div>
          </el-form-item>

          <el-form-item
            label="维度名称 *"
            prop="dimension_name"
            :rules="[
              { required: true, message: '请输入维度名称', trigger: 'blur' },
              {
                max: 100,
                message: '维度名称不能超过100个字符',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="dimensionData.dimension_name"
              placeholder="请输入维度名称"
              maxlength="100"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="维度描述" prop="dimension_description">
            <el-input
              v-model="dimensionData.dimension_description"
              placeholder="请输入维度描述"
              type="textarea"
              rows="2"
            ></el-input>
          </el-form-item>

          <template v-if="isEdit">
            <el-form-item label="创建时间">
              <el-input v-model="dimensionData.created_at" disabled></el-input>
            </el-form-item>
            <el-form-item label="更新时间">
              <el-input v-model="dimensionData.updated_at" disabled></el-input>
            </el-form-item>
          </template>
        </el-form>
      </el-card>

      <!-- 评分配置 -->
      <el-card class="form-section-card">
        <template #header>
          <span class="section-title">评分配置</span>
        </template>
        <el-form
          ref="scoreFormRef"
          :model="dimensionData"
          label-width="120px"
          size="small"
        >
          <el-form-item
            label="最大分值 *"
            prop="max_score"
            :rules="[
              { required: true, message: '请输入最大分值', trigger: 'blur' },
              {
                type: 'number',
                min: 0,
                max: 100,
                message: '请输入0-100之间的数值',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              v-model="dimensionData.max_score"
              placeholder="请输入最大分值"
              :min="0"
              :max="100"
              :step="0.5"
              :precision="1"
            ></el-input-number>
            <span class="unit">分</span>
            <div
              v-if="isEdit && originalMaxScore !== dimensionData.max_score"
              class="change-indicator"
            >
              原值: {{ originalMaxScore }} → 新值:
              {{ dimensionData.max_score }} ⚠️ 已修改
            </div>
          </el-form-item>

          <el-form-item
            label="权重系数"
            prop="weight"
            :rules="[
              {
                type: 'number',
                min: 0,
                max: 10,
                message: '请输入0-10之间的数值',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              v-model="dimensionData.weight"
              placeholder="请输入权重系数（默认1.0）"
              :min="0"
              :max="10"
              :step="0.1"
              :precision="1"
            ></el-input-number>
            <div class="hint-text">默认值: 1.0</div>
            <div
              v-if="isEdit && originalWeight !== dimensionData.weight"
              class="change-indicator"
            >
              原值: {{ originalWeight }} → 新值: {{ dimensionData.weight }} ⚠️
              已修改
            </div>
          </el-form-item>

          <el-form-item
            label="显示顺序"
            prop="display_order"
            :rules="[
              {
                type: 'number',
                min: 0,
                message: '请输入大于等于0的整数',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              v-model="dimensionData.display_order"
              placeholder="请输入显示顺序（默认0）"
              :min="0"
            ></el-input-number>
            <div class="hint-text">数字越小越靠前，默认0</div>
          </el-form-item>

          <el-form-item label="启用状态">
            <el-switch
              v-model="dimensionData.is_enabled"
              active-text="启用"
              inactive-text="禁用"
              :active-value="true"
              :inactive-value="false"
            ></el-switch>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 编辑模式下的配置修改历史 -->
      <el-card
        v-if="isEdit && hasChanges"
        class="form-section-card changes-card"
      >
        <template #header>
          <span class="section-title">配置修改历史</span>
        </template>
        <div class="changes-container">
          <div class="changes-title">
            📝 待保存的更改 ({{ changeCount }}项):
          </div>
          <ul class="changes-list">
            <li v-if="originalMaxScore !== dimensionData.max_score">
              • max_score: {{ originalMaxScore }} →
              {{ dimensionData.max_score }}
            </li>
            <li v-if="originalWeight !== dimensionData.weight">
              • weight: {{ originalWeight }} → {{ dimensionData.weight }}
            </li>
            <li v-if="originalSortOrder !== dimensionData.display_order">
              • display_order: {{ originalSortOrder }} →
              {{ dimensionData.display_order }}
            </li>
            <li v-if="originalStatus !== dimensionData.is_enabled">
              • is_enabled: {{ originalStatus }} →
              {{ dimensionData.is_enabled }}
            </li>
            <li v-if="originalName !== dimensionData.dimension_name">
              • dimension_name: {{ originalName }} →
              {{ dimensionData.dimension_name }}
            </li>
            <li
              v-if="originalDescription !== dimensionData.dimension_description"
            >
              • dimension_description: {{ originalDescription || "空" }} →
              {{ dimensionData.dimension_description || "空" }}
            </li>
          </ul>
        </div>
      </el-card>

      <!-- 可展开的配置区域 -->
      <div v-if="isEdit" class="expandable-configs">
        <el-button
          type="text"
          @click="toggleSection('dataSource')"
          class="section-toggle-btn"
        >
          {{ showSections.dataSource ? "收起" : "展开" }} 数据源配置
        </el-button>
        <el-button
          type="text"
          @click="toggleSection('calculation')"
          class="section-toggle-btn"
        >
          {{ showSections.calculation ? "收起" : "展开" }} 计算配置
        </el-button>
        <el-button
          type="text"
          @click="toggleSection('aggregation')"
          class="section-toggle-btn"
        >
          {{ showSections.aggregation ? "收起" : "展开" }} 聚合配置
        </el-button>
        <span class="toggle-hint"> - 点击展开编辑</span>
      </div>

      <!-- 数据源配置 -->
      <el-card
        v-if="!isEdit || showSections.dataSource"
        class="form-section-card"
      >
        <template #header>
          <span class="section-title">数据源配置</span>
        </template>
        <el-form
          ref="dataSourceFormRef"
          :model="dimensionData.data_source"
          label-width="120px"
          size="small"
        >
          <el-form-item label="数据源类型">
            <el-select
              v-model="dimensionData.data_source_type"
              placeholder="选择数据源类型"
              @change="handleDataSourceTypeChange"
              :loading="metadataLoading"
              filterable
            >
              <el-option
                v-for="type in dataSourceTypes"
                :key="type.type"
                :label="type.name"
                :value="type.type"
              >
                <div>
                  <div>{{ type.name }}</div>
                  <div class="option-description">{{ type.description }}</div>
                </div>
              </el-option>
              <el-option
                v-if="dataSourceTypes.length === 0 && !metadataLoading"
                disabled
                value=""
              >
                暂无数据源类型（使用默认选项）
              </el-option>
              <!-- 如果元数据未加载，提供默认选项 -->
              <template v-if="!metadata.value && !metadataLoading">
                <el-option label="单表查询" value="single_table"></el-option>
                <el-option label="多表关联" value="multi_table"></el-option>
                <el-option label="外部接口" value="external_api"></el-option>
              </template>
            </el-select>
            <div class="hint-text">
              {{
                dataSourceTypes.find(
                  (t) => t.type === dimensionData.data_source_type
                )?.description || "默认: single_table"
              }}
            </div>
          </el-form-item>

          <el-form-item label="配置详情">
            <el-input
              v-model="dataSourceConfigStr"
              type="textarea"
              rows="6"
              placeholder="请输入JSON格式的数据源配置"
              monospace
            ></el-input>
            <el-button
              type="text"
              size="small"
              @click="validateJson('dataSource')"
              class="validate-btn"
            >
              验证JSON
            </el-button>
            <div v-if="jsonErrors.dataSource" class="json-error">
              {{ jsonErrors.dataSource }}
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 计算配置 -->
      <el-card
        v-if="!isEdit || showSections.calculation"
        class="form-section-card"
      >
        <template #header>
          <span class="section-title">计算配置</span>
        </template>
        <el-form
          ref="calculationFormRef"
          :model="dimensionData.calculation"
          label-width="120px"
          size="small"
        >
          <el-form-item label="计算类型">
            <el-select
              v-model="dimensionData.calculation_type"
              placeholder="选择计算类型"
              @change="handleCalculationTypeChange"
              :loading="metadataLoading"
              filterable
            >
              <el-option
                v-for="type in calculationTypes"
                :key="type.type"
                :label="type.name"
                :value="type.type"
              >
                <div>
                  <div>{{ type.name }}</div>
                  <div class="option-description">{{ type.description }}</div>
                </div>
              </el-option>
              <el-option
                v-if="calculationTypes.length === 0 && !metadataLoading"
                disabled
                value=""
              >
                暂无计算类型（使用默认选项）
              </el-option>
              <!-- 如果元数据未加载，提供默认选项 -->
              <template v-if="!metadata.value && !metadataLoading">
                <el-option label="等级映射" value="level_mapping"></el-option>
                <el-option label="加权求和" value="weighted_sum"></el-option>
                <el-option label="阈值判断" value="threshold"></el-option>
                <el-option label="自定义公式" value="formula"></el-option>
              </template>
            </el-select>
            <div class="hint-text">
              {{
                calculationTypes.find(
                  (t) => t.type === dimensionData.calculation_type
                )?.description || "默认: level_mapping"
              }}
            </div>
          </el-form-item>

          <el-form-item label="计算配置">
            <el-input
              v-model="calculationConfigStr"
              type="textarea"
              rows="6"
              placeholder='请输入JSON格式的计算配置，例如：{"high": 10, "medium": 5, "low": 1}'
              :style="{ fontFamily: 'monospace' }"
            ></el-input>
            <el-button
              type="text"
              size="small"
              @click="validateJson('calculation')"
              class="validate-btn"
            >
              验证JSON
            </el-button>
            <div v-if="jsonErrors.calculation" class="json-error">
              {{ jsonErrors.calculation }}
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 聚合配置 -->
      <el-card
        v-if="!isEdit || showSections.aggregation"
        class="form-section-card"
      >
        <template #header>
          <span class="section-title">聚合配置</span>
        </template>
        <el-form
          ref="aggregationFormRef"
          :model="dimensionData.aggregation"
          label-width="120px"
          size="small"
        >
          <el-form-item label="聚合模式">
            <el-select
              v-model="dimensionData.aggregation_mode"
              placeholder="选择聚合模式"
              @change="handleAggregationModeChange"
              :loading="metadataLoading"
              filterable
            >
              <el-option
                v-for="mode in aggregationModes"
                :key="mode.mode"
                :label="mode.name"
                :value="mode.mode"
              >
                <div>
                  <div>{{ mode.name }}</div>
                  <div class="option-description">{{ mode.description }}</div>
                </div>
              </el-option>
              <el-option
                v-if="aggregationModes.length === 0 && !metadataLoading"
                disabled
                value=""
              >
                暂无聚合模式（使用默认选项）
              </el-option>
              <!-- 如果元数据未加载，提供默认选项 -->
              <template v-if="!metadata.value && !metadataLoading">
                <el-option label="最大值" value="max"></el-option>
                <el-option label="最小值" value="min"></el-option>
                <el-option label="平均值" value="average"></el-option>
                <el-option label="求和" value="sum"></el-option>
                <el-option label="优先级" value="priority"></el-option>
              </template>
            </el-select>
            <div class="hint-text">
              {{
                aggregationModes.find(
                  (m) => m.mode === dimensionData.aggregation_mode
                )?.description || "默认: max"
              }}
            </div>
          </el-form-item>

          <el-form-item label="聚合配置">
            <el-input
              v-model="aggregationConfigStr"
              type="textarea"
              rows="6"
              placeholder='请输入JSON格式的聚合配置，例如：{"mode": "max"} 或 {"mode": "priority", "priority": ["critical", "high", "medium", "low"]}'
              :style="{ fontFamily: 'monospace' }"
            ></el-input>
            <el-button
              type="text"
              size="small"
              @click="validateJson('aggregation')"
              class="validate-btn"
            >
              验证JSON
            </el-button>
            <div v-if="jsonErrors.aggregation" class="json-error">
              {{ jsonErrors.aggregation }}
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="isEdit" type="default" @click="handleResetForm">
        重置
      </el-button>
      <el-button
        v-if="isEdit"
        type="primary"
        @click="handleSave"
        :loading="saving"
      >
        保存修改
      </el-button>
      <template v-else>
        <el-button type="default" @click="handlePreview"> 预览配置 </el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          确认创建
        </el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, onMounted, computed } from "vue";
import { ElMessage, ElForm } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import {
  createDimension,
  updateDimension,
  getTemplateList,
  getDimensionConfigMetadata,
} from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  dimensionId: {
    type: String,
    default: "",
  },
  dimensionData: {
    type: Object,
    default: () => ({}),
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["success", "update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const saving = ref(false);
const templates = ref([]);
const templateLoading = ref(false); // 模板搜索加载状态
const templateSearchQuery = ref(""); // 模板搜索关键词
const metadata = ref<any>(null);
const metadataLoading = ref(false);
const selectedTemplate = ref<any>(null);
const showSections = ref({
  dataSource: false,
  calculation: false,
  aggregation: false,
});

// 元数据选项
const dataSourceTypes = computed(() => {
  return metadata.value?.data_source_types || [];
});

const calculationTypes = computed(() => {
  return metadata.value?.calculation_types || [];
});

const aggregationModes = computed(() => {
  return metadata.value?.aggregation_modes || [];
});

const predefinedTemplates = computed(() => {
  return metadata.value?.templates || [];
});

// JSON配置字符串
const dataSourceConfigStr = ref("");
const calculationConfigStr = ref("");
const aggregationConfigStr = ref("");
const jsonErrors = ref({
  dataSource: "",
  calculation: "",
  aggregation: "",
});

// 表单引用
const baseFormRef = ref<InstanceType<typeof ElForm>>();
const scoreFormRef = ref<InstanceType<typeof ElForm>>();
const dataSourceFormRef = ref<InstanceType<typeof ElForm>>();
const calculationFormRef = ref<InstanceType<typeof ElForm>>();
const aggregationFormRef = ref<InstanceType<typeof ElForm>>();

// 原始值，用于编辑时比较
const originalMaxScore = ref(0);
const originalWeight = ref(0);
const originalSortOrder = ref(0);
const originalStatus = ref<boolean>(true);
const originalName = ref("");
const originalDescription = ref("");

// 维度数据
const dimensionData = ref<any>({
  id: "",
  dimension_code: "",
  dimension_name: "",
  dimension_description: "",
  template_id: "",
  template_name: "",
  max_score: 20,
  weight: 1.0,
  display_order: 0,
  is_enabled: true,
  data_source_type: "single_table",
  data_source_config: {},
  calculation_type: "level_mapping",
  calculation_config: {},
  aggregation_mode: "max",
  aggregation_config: {},
  created_at: "",
  updated_at: "",
});

// 检查是否有修改
const hasChanges = computed(() => {
  return (
    originalMaxScore.value !== dimensionData.value.max_score ||
    originalWeight.value !== dimensionData.value.weight ||
    originalSortOrder.value !== dimensionData.value.display_order ||
    originalStatus.value !== dimensionData.value.is_enabled ||
    originalName.value !== dimensionData.value.dimension_name ||
    originalDescription.value !== dimensionData.value.dimension_description
  );
});

// 计算修改数量
const changeCount = computed(() => {
  let count = 0;
  if (originalMaxScore.value !== dimensionData.value.max_score) count++;
  if (originalWeight.value !== dimensionData.value.weight) count++;
  if (originalSortOrder.value !== dimensionData.value.display_order) count++;
  if (originalStatus.value !== dimensionData.value.is_enabled) count++;
  if (originalName.value !== dimensionData.value.dimension_name) count++;
  if (originalDescription.value !== dimensionData.value.dimension_description)
    count++;
  return count;
});

// 重置表单（需要在 watch 之前定义）
const resetForm = () => {
  dimensionData.value = {
    id: "",
    dimension_code: "",
    dimension_name: "",
    dimension_description: "",
    template_id: "",
    template_name: "",
    max_score: 20,
    weight: 1.0,
    display_order: 0,
    is_enabled: true,
    data_source_type: "single_table",
    data_source_config: {},
    calculation_type: "level_mapping",
    calculation_config: {},
    aggregation_mode: "max",
    aggregation_config: {},
    created_at: "",
    updated_at: "",
  };

  // 重置原始值
  originalMaxScore.value = 0;
  originalWeight.value = 0;
  originalSortOrder.value = 0;
  originalStatus.value = true;
  originalName.value = "";
  originalDescription.value = "";

  // 重置JSON配置
  dataSourceConfigStr.value = JSON.stringify({}, null, 2);
  calculationConfigStr.value = JSON.stringify({}, null, 2);
  aggregationConfigStr.value = JSON.stringify({}, null, 2);
  jsonErrors.value = {
    dataSource: "",
    calculation: "",
    aggregation: "",
  };

  // 重置表单验证
  if (baseFormRef.value) baseFormRef.value.resetFields();
  if (scoreFormRef.value) scoreFormRef.value.resetFields();
  if (dataSourceFormRef.value) dataSourceFormRef.value.resetFields();
  if (calculationFormRef.value) calculationFormRef.value.resetFields();
  if (aggregationFormRef.value) aggregationFormRef.value.resetFields();
};

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val) {
      // 对话框打开时，确保数据已加载
      // 模板列表使用远程搜索，不在打开时自动加载
      // if (templates.value.length === 0) {
      //   fetchTemplates();
      // }
      if (!metadata.value) {
        fetchMetadata();
      }
    } else {
      // 重置表单
      resetForm();
      selectedTemplate.value = null;
    }
  }
);

// 监听维度数据变化（编辑模式）
watch(
  () => props.dimensionData,
  (data) => {
    if (data && Object.keys(data).length > 0 && visible.value && props.isEdit) {
      loadDimensionData(data);
    } else if (!data || Object.keys(data).length === 0) {
      if (!props.isEdit) {
        resetForm();
      }
    }
  },
  { deep: true, immediate: true }
);

// 监听JSON配置变化
watch(
  () => dimensionData.value.data_source_config,
  (config) => {
    try {
      dataSourceConfigStr.value = JSON.stringify(config || {}, null, 2);
    } catch (e) {
      console.error("Failed to stringify data source config", e);
    }
  },
  { deep: true }
);

watch(
  () => dimensionData.value.calculation_config,
  (config) => {
    try {
      calculationConfigStr.value = JSON.stringify(config || {}, null, 2);
    } catch (e) {
      console.error("Failed to stringify calculation config", e);
    }
  },
  { deep: true }
);

watch(
  () => dimensionData.value.aggregation_config,
  (config) => {
    try {
      aggregationConfigStr.value = JSON.stringify(config || {}, null, 2);
    } catch (e) {
      console.error("Failed to stringify aggregation config", e);
    }
  },
  { deep: true }
);

// 页面初始化
onMounted(() => {
  fetchTemplates();
  fetchMetadata();

  // 如果是编辑模式且有数据，加载数据
  if (
    props.isEdit &&
    props.dimensionData &&
    Object.keys(props.dimensionData).length > 0
  ) {
    loadDimensionData(props.dimensionData);
  } else {
    // 初始化默认JSON配置
    dataSourceConfigStr.value = JSON.stringify({}, null, 2);
    calculationConfigStr.value = JSON.stringify({}, null, 2);
    aggregationConfigStr.value = JSON.stringify({}, null, 2);
  }
});

// 获取模板列表（带搜索功能）
const fetchTemplates = async (query: string = "") => {
  templateLoading.value = true;
  try {
    const params: any = {
      page: 1,
      page_size: 10,
      order_by: "created_at",
      order_direction: "desc",
    };

    // 如果有搜索关键词，添加到 filters 中
    if (query && query.trim()) {
      params.filters = {
        template_name: query.trim(),
      };
    }

    const response = await getTemplateList(params);

    templates.value = response.data.items;

    console.log("模板列表:", templates.value);
  } catch (error: any) {
    console.error("获取模板列表失败:", error);
    ElMessage.error(error?.message || "获取模板列表失败");
    templates.value = [];
  } finally {
    templateLoading.value = false;
  }
};

// 模板远程搜索方法
const handleTemplateSearch = (query: string) => {
  templateSearchQuery.value = query;
  if (query) {
    // 有搜索关键词时，调用接口搜索
    fetchTemplates(query);
  } else {
    // 清空搜索时，也刷新列表（获取默认列表）
    fetchTemplates();
  }
};

// 模板选择框获得焦点时
const handleTemplateFocus = () => {
  // 如果当前没有模板列表，且没有搜索关键词，加载默认列表
  if (templates.value.length === 0 && !templateSearchQuery.value) {
    fetchTemplates();
  }
};

// 模板选择框清空时
const handleTemplateClear = () => {
  templateSearchQuery.value = "";
  // 清空时可以选择是否重新加载默认列表
  // fetchTemplates();
};

// 获取元数据
const fetchMetadata = async () => {
  metadataLoading.value = true;
  try {
    const response = await getDimensionConfigMetadata();
    console.log("元数据响应:", response);

    // 处理响应数据（拦截器已经解析了JSON字符串）
    // 响应结构：{ code: 2000, data: {...}, message: '...' }
    let metadataData = null;
    if (response?.data) {
      // 拦截器返回的是解析后的对象，直接使用 data 字段
      metadataData = response.data;
    } else if (response) {
      // 如果直接是data对象（兜底）
      metadataData = response;
    }

    metadata.value = metadataData;
    console.log("解析后的元数据:", metadata.value);

    // 验证数据是否正确
    if (!metadata.value) {
      console.warn("元数据为空");
      ElMessage.warning("获取配置元数据为空，将使用默认选项");
    } else {
      // 验证数据结构
      console.log("元数据获取成功:", {
        dataSourceTypes: metadata.value.data_source_types?.length || 0,
        calculationTypes: metadata.value.calculation_types?.length || 0,
        aggregationModes: metadata.value.aggregation_modes?.length || 0,
        templates: metadata.value.templates?.length || 0,
        version: metadata.value.version,
        updatedAt: metadata.value.updated_at,
      });
    }
  } catch (error: any) {
    console.error("获取配置元数据失败:", error);
    ElMessage.error(error?.message || "获取配置元数据失败");
    metadata.value = null;
  } finally {
    metadataLoading.value = false;
  }
};

// 加载维度数据（从props传入）
const loadDimensionData = (data: any) => {
  dimensionData.value = {
    id: data.id,
    dimension_code: data.dimension_code,
    dimension_name: data.dimension_name,
    dimension_description: data.dimension_description || "",
    template_id: data.template_id,
    template_name: data.template_name,
    max_score: data.max_score,
    weight: data.weight || 1.0,
    display_order: data.display_order || 0,
    is_enabled: data.is_enabled !== undefined ? data.is_enabled : true,
    data_source_type: data.data_source_type || "single_table",
    data_source_config: data.data_source_config || {},
    calculation_type: data.calculation_type || "level_mapping",
    calculation_config: data.calculation_config || {},
    aggregation_mode: data.aggregation_mode || "max",
    aggregation_config: data.aggregation_config || {},
    created_at: data.created_at,
    updated_at: data.updated_at,
  };

  // 保存原始值用于比较
  originalMaxScore.value = data.max_score;
  originalWeight.value = data.weight || 1.0;
  originalSortOrder.value = data.display_order || 0;
  originalStatus.value = data.is_enabled !== undefined ? data.is_enabled : true;
  originalName.value = data.dimension_name;
  originalDescription.value = data.dimension_description || "";

  // 初始化JSON配置字符串
  dataSourceConfigStr.value = JSON.stringify(
    dimensionData.value.data_source_config,
    null,
    2
  );
  calculationConfigStr.value = JSON.stringify(
    dimensionData.value.calculation_config,
    null,
    2
  );
  aggregationConfigStr.value = JSON.stringify(
    dimensionData.value.aggregation_config,
    null,
    2
  );
};

// 切换展开/收起配置区域
const toggleSection = (section) => {
  showSections.value[section] = !showSections.value[section];
};

// 数据源类型变化
const handleDataSourceTypeChange = (type: string) => {
  // 根据元数据中的示例设置默认配置
  const dataSourceType = dataSourceTypes.value.find((t) => t.type === type);
  if (dataSourceType && dataSourceType.example) {
    dimensionData.value.data_source_config = JSON.parse(
      JSON.stringify(dataSourceType.example)
    );
    dataSourceConfigStr.value = JSON.stringify(
      dimensionData.value.data_source_config,
      null,
      2
    );
  } else if (
    Object.keys(dimensionData.value.data_source_config || {}).length === 0
  ) {
    // 如果没有示例，使用空对象
    dimensionData.value.data_source_config = {};
    dataSourceConfigStr.value = JSON.stringify({}, null, 2);
  }
};

// 计算类型变化
const handleCalculationTypeChange = (type: string) => {
  const calculationType = calculationTypes.value.find((t) => t.type === type);
  if (calculationType && calculationType.example) {
    dimensionData.value.calculation_config = JSON.parse(
      JSON.stringify(calculationType.example)
    );
    calculationConfigStr.value = JSON.stringify(
      dimensionData.value.calculation_config,
      null,
      2
    );
  } else if (
    Object.keys(dimensionData.value.calculation_config || {}).length === 0
  ) {
    dimensionData.value.calculation_config = {};
    calculationConfigStr.value = JSON.stringify({}, null, 2);
  }
};

// 聚合模式变化
const handleAggregationModeChange = (mode: string) => {
  const aggregationMode = aggregationModes.value.find((m) => m.mode === mode);
  if (aggregationMode && aggregationMode.example) {
    dimensionData.value.aggregation_config = JSON.parse(
      JSON.stringify(aggregationMode.example)
    );
    aggregationConfigStr.value = JSON.stringify(
      dimensionData.value.aggregation_config,
      null,
      2
    );
  } else if (
    Object.keys(dimensionData.value.aggregation_config || {}).length === 0
  ) {
    dimensionData.value.aggregation_config = {};
    aggregationConfigStr.value = JSON.stringify({}, null, 2);
  }
};

// 模板选择处理
const handleTemplateSelect = (template: any) => {
  if (!template) return;

  // 应用模板的维度配置
  if (template.dimensions && template.dimensions.length > 0) {
    const firstDimension = template.dimensions[0];

    // 填充基础信息（需要用户手动选择模板）
    dimensionData.value.dimension_name = firstDimension.dimension_name || "";
    dimensionData.value.dimension_code = firstDimension.dimension_code || "";
    dimensionData.value.dimension_description =
      firstDimension.dimension_description || "";
    dimensionData.value.max_score = firstDimension.max_score || 20;
    dimensionData.value.weight = firstDimension.weight || 1.0;

    // 填充配置
    dimensionData.value.data_source_type =
      firstDimension.data_source_type || "single_table";
    dimensionData.value.data_source_config =
      firstDimension.data_source_config || {};
    dimensionData.value.calculation_type =
      firstDimension.calculation_type || "level_mapping";
    dimensionData.value.calculation_config =
      firstDimension.calculation_config || {};
    dimensionData.value.aggregation_mode =
      firstDimension.aggregation_mode || "max";
    dimensionData.value.aggregation_config =
      firstDimension.aggregation_config || {};

    // 更新JSON字符串
    dataSourceConfigStr.value = JSON.stringify(
      dimensionData.value.data_source_config,
      null,
      2
    );
    calculationConfigStr.value = JSON.stringify(
      dimensionData.value.calculation_config,
      null,
      2
    );
    aggregationConfigStr.value = JSON.stringify(
      dimensionData.value.aggregation_config,
      null,
      2
    );

    ElMessage.success(`已应用模板: ${template.name}`);
  }
};

// 验证JSON格式
const validateJson = (type: string) => {
  let configStr: string;

  if (type === "dataSource") {
    configStr = dataSourceConfigStr.value;
  } else if (type === "calculation") {
    configStr = calculationConfigStr.value;
  } else if (type === "aggregation") {
    configStr = aggregationConfigStr.value;
  } else {
    return false;
  }

  try {
    if (!configStr.trim()) {
      // 允许空配置，设置为空对象
      const parsed = {};
      if (type === "dataSource") {
        dimensionData.value.data_source_config = parsed;
      } else if (type === "calculation") {
        dimensionData.value.calculation_config = parsed;
      } else if (type === "aggregation") {
        dimensionData.value.aggregation_config = parsed;
      }
      jsonErrors.value[type] = "";
      return true;
    }

    const parsed = JSON.parse(configStr);

    // 更新对应的配置对象
    if (type === "dataSource") {
      dimensionData.value.data_source_config = parsed;
    } else if (type === "calculation") {
      dimensionData.value.calculation_config = parsed;
    } else if (type === "aggregation") {
      dimensionData.value.aggregation_config = parsed;
    }

    jsonErrors.value[type] = "";
    ElMessage.success("JSON格式验证通过");
    return true;
  } catch (e: any) {
    jsonErrors.value[type] = `JSON格式错误: ${e.message}`;
    return false;
  }
};

// 表单验证
const validateForm = async () => {
  // 先验证JSON配置
  const dataSourceValid = validateJson("dataSource");
  const calculationValid = validateJson("calculation");
  const aggregationValid = validateJson("aggregation");

  if (!dataSourceValid || !calculationValid || !aggregationValid) {
    return false;
  }

  // 验证表单字段
  const baseValid = (await baseFormRef.value?.validate()) || false;
  const scoreValid = (await scoreFormRef.value?.validate()) || false;

  return baseValid && scoreValid;
};

// 保存维度配置
const handleSave = async () => {
  if (!(await validateForm())) {
    return;
  }

  saving.value = true;
  try {
    if (props.isEdit) {
      // 更新维度 - 只发送需要更新的字段
      const updateData: any = {
        dimension_id: Number(dimensionData.value.id),
      };

      if (dimensionData.value.dimension_name !== originalName.value) {
        updateData.dimension_name = dimensionData.value.dimension_name;
      }
      if (
        dimensionData.value.dimension_description !== originalDescription.value
      ) {
        updateData.dimension_description =
          dimensionData.value.dimension_description || "";
      }
      if (dimensionData.value.max_score !== originalMaxScore.value) {
        updateData.max_score = dimensionData.value.max_score;
      }
      if (dimensionData.value.weight !== originalWeight.value) {
        updateData.weight = dimensionData.value.weight;
      }
      if (dimensionData.value.display_order !== originalSortOrder.value) {
        updateData.display_order = dimensionData.value.display_order;
      }
      if (dimensionData.value.is_enabled !== originalStatus.value) {
        updateData.is_enabled = dimensionData.value.is_enabled;
      }

      // 配置字段
      updateData.data_source_type = dimensionData.value.data_source_type;
      updateData.data_source_config =
        dimensionData.value.data_source_config || {};
      updateData.calculation_type = dimensionData.value.calculation_type;
      updateData.calculation_config =
        dimensionData.value.calculation_config || {};
      updateData.aggregation_mode = dimensionData.value.aggregation_mode;
      updateData.aggregation_config =
        dimensionData.value.aggregation_config || {};

      const result = await updateDimension(updateData);
      if (result.code === 2000) {
        ElMessage.success("维度更新成功");
        emit("success");
        emit("update:modelValue", false);
      } else {
        ElMessage.error(result.message || "维度更新失败");
      }
    } else {
      // 创建维度
      const createData = {
        template_id: Number(dimensionData.value.template_id),
        dimension_code: dimensionData.value.dimension_code,
        dimension_name: dimensionData.value.dimension_name,
        dimension_description: dimensionData.value.dimension_description || "",
        max_score: dimensionData.value.max_score,
        weight: dimensionData.value.weight || 1.0,
        display_order: dimensionData.value.display_order || 0,
        is_enabled:
          dimensionData.value.is_enabled !== undefined
            ? dimensionData.value.is_enabled
            : true,
        data_source_type:
          dimensionData.value.data_source_type || "single_table",
        data_source_config: dimensionData.value.data_source_config || {},
        calculation_type:
          dimensionData.value.calculation_type || "level_mapping",
        calculation_config: dimensionData.value.calculation_config || {},
        aggregation_mode: dimensionData.value.aggregation_mode || "max",
        aggregation_config: dimensionData.value.aggregation_config || {},
      };

      const result = await createDimension(createData);
      if (result.code === 2000) {
        ElMessage.success("维度创建成功");
        emit("success");
        emit("update:modelValue", false);
      } else {
        ElMessage.error(result.message || "维度创建失败");
      }
    }
  } catch (error: any) {
    ElMessage.error(
      error?.message || (props.isEdit ? "维度更新失败" : "维度创建失败")
    );
  } finally {
    saving.value = false;
  }
};

// 预览配置
const handlePreview = () => {
  if (!validateForm()) {
    return;
  }

  // 这里可以实现配置预览逻辑
  ElMessage.info("配置预览功能待实现");
};

// 重置表单（编辑模式）
const handleResetForm = () => {
  dimensionData.value.max_score = originalMaxScore.value;
  dimensionData.value.weight = originalWeight.value;
  dimensionData.value.display_order = originalSortOrder.value;
  dimensionData.value.is_enabled = originalStatus.value;
  dimensionData.value.dimension_name = originalName.value;
  dimensionData.value.dimension_description = originalDescription.value;
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭前处理
const handleBeforeClose = () => {
  emit("update:modelValue", false);
  return true;
};
</script>

<style scoped lang="scss">
.form-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.form-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.changes-card {
  border-left: 4px solid #faad14;
}

.changes-container {
  padding: 10px 0;
}

.changes-title {
  font-weight: 500;
  margin-bottom: 10px;
  color: #faad14;
}

.changes-list {
  padding-left: 20px;
  font-size: 13px;
}

.changes-list li {
  margin-bottom: 5px;
}

.hint-text {
  margin-top: 5px;
  font-size: 12px;
  color: #86909c;
}

.unit {
  margin-left: 5px;
  color: #86909c;
}

.change-indicator {
  margin-top: 5px;
  font-size: 12px;
  color: #faad14;
  padding: 2px 5px;
  background-color: #fffbe6;
  border-radius: 3px;
}

.expandable-configs {
  margin-bottom: 16px;
  padding: 10px 0;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.section-toggle-btn {
  padding: 0;
}

.toggle-hint {
  color: #86909c;
  font-size: 13px;
}

.validate-btn {
  margin-top: 5px;
  padding: 0;
  font-size: 12px;
}

.json-error {
  margin-top: 5px;
  font-size: 12px;
  color: #f5222d;
  word-break: break-all;
}

.option-description {
  font-size: 12px;
  color: #86909c;
  margin-top: 2px;
}

.error-text {
  color: #f5222d;
}

.template-card {
  border-left: 4px solid #1890ff;
}

::v-deep textarea[monospace] {
  font-family: monospace;
  line-height: 1.5;
}

::v-deep .el-select-dropdown__item {
  padding: 8px 20px;
}
</style>
